/* @flow */

import React, { Component } from 'react';
import {View,Text,StyleSheet,Image,SectionList,Dimensions,TouchableOpacity,FlatList} from 'react-native';
// 导航组件
import {StackNavigator,TabNavigator,DrawerNavigator,NavigationActions,} from 'react-navigation';

import { connect } from 'react-redux';

import SlideShowView from './Home/SlideShowView.js';
import HomeStyle from './Home/HomeStyle.js';
import CategoryItem from './Home/CategoryItem.js';
import AllCategoryFlatList from './Home/AllCategoryFlatList.js';
import SectionFooterView from './Home/HomeSectionFooterView.js';
import SectionHeaderView from './Home/HomeSectionHeaderView.js';

let sWidth = Dimensions.get('window').width;
let sHeight = Dimensions.get('window').height;
let sRat = sWidth/375;
let hotRecommendGapWidth = (sWidth-110*3)/4;
let fmRecommendGapWidth = (sWidth-65*4)/5;

class AppHome extends Component {

  static navigationOptions = ({navigation,screenProps}) => {
    const {navigate,state,params} = navigation;
    var title =params&& params.title  ? state.params.title:'title';

    return {
      // headerTitle: title,
      header: <View></View>,

      //tabbar
      tabBarIcon : ({focused, tintColor }) => {

        return(
          <Image
            source={focused ? require('../img/tabicon/shouyeSelectedXiong1.png'):require('../img/tabicon/shouyeXiong1.png')}
            style={[styles.icon]}
          />)
      },

    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.index != this.props.index) {
      this._dispatchParams();
    }
  }

  _dispatchParams = () => {
    var {navigate,state} = this.props.navigation;
    var index = this.props.index?this.props.index:0;
    console.log("现在的中转index:"+index);
    if (this.props&&this.props.index&&this.props.index!=index) {
      console.log('进来了');
      this.props.navigation.dispatch(NavigationActions.setParams({
        params: { title:'Hello home',index:this.props.index },
        key: this.props.navigation.state.key,
      }))
    }
  }

  constructor(props){
  	super(props);
  	this.state = {
      dataArr : [],
      slideShowData : [],
      categoryData : [],
    };
  }

  componentDidMount() {
      this.fetchData();
  }

  fetchData(){
    let requestUrl = 'http://yiapi.xinli001.com/fm/home-list.json?key=c0d28ec0954084b4426223366293d190';
    let map = {
      method:'GET'
    }
    fetch(requestUrl, map)
      .then((response) => response.json())
      .then((responseData) => {
        //console.log(responseData);
        let jsonData = responseData.data;

        var initialArr = [
                          {key:'热门推荐', data:jsonData.hotfm, footTitle:''},
                          {key:'最新心理课', data:jsonData.newlesson, footTitle:'更多心理课'},
                          {key:'最新FM', data:jsonData.newfm, footTitle:'更多FM'},
                          {key:'心理电台推荐', data:jsonData.diantai, footTitle:'更多电台'}
                        ];
        this.setState({
          slideShowData : jsonData.tuijian,
          categoryData : jsonData.category,
          dataArr : initialArr,
        })
      })
      .catch((error) => {
        console.log(error);
        alert('失败');
      })
  }

  render() {
    return (
      <View style = {{backgroundColor:'rgb(242,242,242)'}}>
        <SectionList
          ListHeaderComponent = {this._listHeaderComponent}
          ListEmptyComponent = {this._ListEmptyComponent}
          renderSectionHeader = {this._renderSectionHeader}
          renderSectionFooter = {this._renderSectionFooter}
          keyExtractor = {this._keyExtractor}
          sections = {[
            {
              data:this.state.dataArr[0] && this.state.dataArr[0].data ? this.state.dataArr[0].data:[],
              key:this.state.dataArr[0]&& this.state.dataArr[0].key?this.state.dataArr[0].key:'',
              footTitle:this.state.dataArr[0]&& this.state.dataArr[0].footTitle?this.state.dataArr[0].footTitle:'',
              renderItem:this._renderHotTuiJianItem
            },
            {
              data:this.state.dataArr[1] && this.state.dataArr[1].data ? this.state.dataArr[1].data:[],
              key:this.state.dataArr[1]&& this.state.dataArr[1].key?this.state.dataArr[1].key:'',
              footTitle:this.state.dataArr[1]&& this.state.dataArr[1].footTitle?this.state.dataArr[1].footTitle:'',
              renderItem:this._renderNewItem
            },
            {
              data:this.state.dataArr[2] && this.state.dataArr[2].data ? this.state.dataArr[2].data:[],
              key:this.state.dataArr[2]&& this.state.dataArr[2].key?this.state.dataArr[2].key:'',
              footTitle:this.state.dataArr[2]&& this.state.dataArr[2].footTitle?this.state.dataArr[2].footTitle:'',
              renderItem:this._renderNewItem
            },
            {
              data:this.state.dataArr[3] && this.state.dataArr[3].data ? this.state.dataArr[3].data:[],
              key:this.state.dataArr[3]&& this.state.dataArr[3].key?this.state.dataArr[3].key:'',
              footTitle:this.state.dataArr[3]&& this.state.dataArr[3].footTitle?this.state.dataArr[3].footTitle:'',
              renderItem:this._renderDianTaiTuiJianItem
            },
          ]}
          contentContainerStyle = {styles.cellStyle}

          stickySectionHeadersEnabled = {false}
          ListFooterComponent = {this._listFooterComponent}
          style = {{backgroundColor:'#ffffff'}}
          numColumns = {4}
          showsVerticalScrollIndicator = {false}
        />
      </View>
    );
  }

  _listFooterComponent = () => {
    return(
      <View style = {{width:sWidth, height:12, backgroundColor:'rgb(242,242,242)'}}>

      </View>
    );
  }

  _ListEmptyComponent = () => {
    return(
      <View style={{justifyContent:'center', alignItems:'center'}}>
        <Text>空空的list列表</Text>
      </View>
    );
  }

  _keyExtractor = (item, index) => {
    return item.id;
  }

  _renderSectionHeader = ({section}) => {
    return(
      <SectionHeaderView
        headerTitle = {section.key}
      />
    );
  }

  _renderSectionFooter = ({section}) => {
    //console.log(section);
    return(
      <TouchableOpacity
        onPress = {() => {
          console.log(section.key);
          let url = '';
          if (section.key === '最新心理课') {
            url = 'http://bapi.xinli001.com/fm2/broadcast_list.json/?rows=15&offset=0&is_teacher=1&key=c0d28ec0954084b4426223366293d190';
            var footerObject = {name:section.key, id:url}
            this.props.navigation.navigate('Detail', {info: footerObject})
          }else if (section.key === '最新FM') {
            url = 'http://bapi.xinli001.com/fm2/broadcast_list.json/?rows=15&offset=0&is_teacher=0&key=c0d28ec0954084b4426223366293d190';
            var footerObject = {name:section.key, id:url}
            this.props.navigation.navigate('Detail', {info: footerObject})
          }else if (section.key === '心理电台推荐') {
            url = 'http://yiapi.xinli001.com/fm/diantai-page.json?key=c0d28ec0954084b4426223366293d190';
            var footerObject = {name:'发现主播', url:url}
            this.props.navigation.navigate('MoreFM', {info: footerObject})
          }else {

          }
        }}
      >
        <SectionFooterView
          footerTitle = {section.footTitle}
        />
      </TouchableOpacity>
    );
  }

  _sectionFooterPressedOn(key) {
    console.log(key);
    let url = '';
    if (key === '最新心理课') {
      url = 'http://bapi.xinli001.com/fm2/broadcast_list.json/?rows=15&offset=0&is_teacher=1&key=c0d28ec0954084b4426223366293d190';
    }else if (key === '最新FM') {
      url = 'http://bapi.xinli001.com/fm2/broadcast_list.json/?rows=15&offset=0&is_teacher=0&key=c0d28ec0954084b4426223366293d190';
    }

    var footerObject = {name:key, id:url}
    console.log(footerObject);
    this.props.navigation.navigate('Detail', {info: footerObject})
  }

  _renderHotTuiJianItem = ({item, index}) => {
    //console.log(item);
    return(
      <TouchableOpacity
        onPress = {() => this.props.navigation.navigate('FMPlayer', {info: item})}
        //onPress = {(item) => this._jumpToFMPlayerView(item)}
      >
        <View style={{width:110, backgroundColor:'#ffffff', marginLeft:hotRecommendGapWidth, }}>
          <Image
            style = {{width:110, height:110}}
            source = {{uri:item.cover}}
          />
          <Text style = {{marginTop:6, marginBottom:20, width:110, color:'rgb(146,146,146)', fontSize:13}}
            numberOfLines = {2}
          >
            {item.title}
          </Text>
        </View>
      </TouchableOpacity>
    );
  }

  _jumpToFMPlayerView (item) {
    this.props.navigation.navigate('FMPlayer', {info: item})
  }

  _renderNewItem = ({item, index}) => {
    return(
      <TouchableOpacity
        onPress = {() => this.props.navigation.navigate('FMPlayer', {info: item})}
      >
        <View style = {{width:sWidth, backgroundColor:'#ffffff', flexDirection:'row'}}>
          <View style = {{width:60,marginBottom: 15}}>
            <Image
              style = {{width:40, height: 40,marginLeft:10}}
              source = {{uri:item.cover}}
            />
          </View>
          <View style = {{marginBottom: 15, width:sWidth-70}}>
            <Text style = {{fontSize:15, color:'rgb(95,95,95)'}}
              numberOfLines = {1}
            >
              {item.title}
            </Text>
            <Text style = {{fontSize:12, color:'rgb(187,188,187)', marginTop:5}}>{item.speak}</Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  _renderDianTaiTuiJianItem = ({item, index}) => {
    return(
      <View style = {{width:65, backgroundColor:'#ffffff', alignItems:'center', marginLeft:fmRecommendGapWidth}}>
        {/* <View style = {{backgroundColor:'#ffffff', alignItems:'center'}}> */}
        <Image
          style = {{width:65, height:65, borderRadius:32}}
          source = {{uri: item.cover}}
          //borderRadius = {0.5}
        />
        <Text style = {{width: 60, color:'gray', marginTop:10, marginBottom:15, fontSize:11, textAlign:'center'}}>
          {item.title}
        </Text>
      </View>
    );
  }

  _listHeaderComponent = () => {
    return(
      <View>
        <SlideShowView
          slideShowData = {this.state.slideShowData}
        />

        {/* <AllCategoryFlatList
          categoryData = {this.state.categoryData}
          onPress = {this.categoryItemPressed}
        /> */}
        <View style={styles.container}>
          <FlatList
            keyExtractor={this._keyExtractor}
            renderItem = {this._flatListRenderItem}
            data={this.state.categoryData}
            numColumns={4}
          />
        </View>
      </View>
    );
  }

  _flatListRenderItem = ({item}) => {
    return(
      <TouchableOpacity
        onPress = {() => this.props.navigation.navigate('Detail', { info: item})}
      >
        <CategoryItem
          cover = {item.cover}
          name = {item.name}
        />
      </TouchableOpacity>
    );
  }
  categoryItemPressed = () => {

  }
}


//用来获取更新后的数据   监听数据更新
const mapStateToProps = (state,ownProps) => {
  if (state.nav) {
    console.log("改变了index:"+state.nav.index);
  }
  return {
    index: state.nav.index,
  }
}

export default connect(mapStateToProps)(AppHome)

const styles = StyleSheet.create({
  cellStyle:{
      flexDirection:'row',
      flexWrap:'wrap',
  },
  container: {
    height:170,
    width:sWidth,
    backgroundColor:'#ffffff',
  },
});
